package com.lbs.jiepiaisi.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;


import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CircleOptions;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.core.SuggestionCity;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.amap.api.services.poisearch.PoiSearch.OnPoiSearchListener;
import com.amap.api.services.poisearch.PoiSearch.SearchBound;
import com.lbs.jiepiaisi.R;
import com.lbs.jiepiaisi.adapter.LocationListAdapter;
import com.lbs.jiepiaisi.base.BaseActivity;
import com.lbs.jiepiaisi.bean.PoiData;
import com.lbs.jiepiaisi.bean.TrackEntity;
import com.lbs.jiepiaisi.manager.MyPoiOverlay;
import com.lbs.jiepiaisi.utils.Constant;
import com.lbs.jiepiaisi.view.WaitingDialogControll;


import java.util.ArrayList;
import java.util.List;

public class PoiAroundSearchActivity extends BaseActivity implements OnClickListener,
        AMap.OnMapClickListener, AMap.InfoWindowAdapter, AMap.OnMarkerClickListener,
        OnPoiSearchListener, LocationSource, AMapLocationListener, LocationListAdapter.OnItemClickListener {
    private MapView mapview;
    private AMap mAMap;
    private PoiResult poiResult; // poi返回的结果
    private int currentPage = 0;// 当前页面，从0开始计数
    private PoiSearch.Query query;// Poi查询条件类
    private LatLonPoint lp;//
    private Marker locationMarker; // 选择的点
    private Marker detailMarker;
    private Marker mlastMarker;
    private PoiSearch poiSearch;
    private myPoiOverlay poiOverlay;// poi图层
    private List<PoiItem> poiItems;// poi数据
    private RelativeLayout mPoiDetail;
    private TextView mPoiName, mPoiAddress;
    private String keyWord = "餐饮服务";
    private String city = "北京市";

    private RecyclerView mListDataRv;


    private AMapLocationClient mLocationClient;

    private LocationSource.OnLocationChangedListener mListener;

    //收起
    private LinearLayout mGetUpLin;
    //导航
    private Button mNavBtn;

    //是否是周边搜索跳转过来的
    private boolean isSearch = false;

    private PoiData searchData;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isTemplate = true;
        super.onCreate(savedInstanceState);
        setContentView(R.layout.poiaroundsearch_activity);
        mapview = (MapView) findViewById(R.id.mapView);
        mapview.onCreate(savedInstanceState);
        WaitingDialogControll.showWaitingDialog(this);
        keyWord = getIntent().getStringExtra("keyWord");
        isSearch = getIntent().getBooleanExtra("isSearch", false);
        searchData = (PoiData) getIntent().getSerializableExtra("resultView");
        init();
        setListener();
        titleView.setText(keyWord);
    }

    private void setListener() {
        mGetUpLin.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mListDataRv.setVisibility(View.VISIBLE);
                mGetUpLin.setVisibility(View.GONE);
                whetherToShowDetailInfo(false);
                if (mlastMarker != null) {
                    resetlastmarker();
                }

            }
        });
        mNavBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {


                //直接导航
                //步行模式 3
                //驾车模式 2
                int routeType = 2;// 标识为驾车模式
                Intent intent = new Intent(PoiAroundSearchActivity.this, AccountStartNaviActivity.class);
                if (!isSearch) {
                    //终点
                    intent.putExtra("getGdLat", String.valueOf(mCurrentPoi.getLatLonPoint().getLatitude()));
                    intent.putExtra("getGdLng", String.valueOf(mCurrentPoi.getLatLonPoint().getLongitude()));
                } else {
                    intent.putExtra("getGdLat", String.valueOf(searchData.getLat()));
                    intent.putExtra("getGdLng", String.valueOf(searchData.getLng()));
                }

                //起点
                intent.putExtra("startGdLat", String.valueOf(lp.getLatitude()));
                intent.putExtra("startGdlng", String.valueOf(lp.getLongitude()));
                //驾车方式
                intent.putExtra("routeType", routeType);

                startActivity(intent);


            }
        });
    }


    /**
     * 初始化AMap对象
     */
    private void init() {
        if (mAMap == null) {
            mAMap = mapview.getMap();
            if (mAMap != null) {
                mAMap.setOnMapClickListener(this);
                mAMap.setOnMarkerClickListener(this);
                mAMap.setInfoWindowAdapter(this);
            }

//			locationMarker = mAMap.addMarker(new MarkerOptions()
//					.anchor(0.5f, 0.5f)
//					.icon(BitmapDescriptorFactory
//							.fromBitmap(BitmapFactory.decodeResource(getResources(), R.mipmap.direct)))
//					.position(new LatLng(lp.getLatitude(), lp.getLongitude())));
        }
        setup();
        setUpMap();
        //周边搜索跳转
        if (isSearch) {
            mListDataRv.setVisibility(View.GONE);
            mPoiDetail.setVisibility(View.VISIBLE);
        }

    }

    private void setup() {
        mPoiDetail = (RelativeLayout) findViewById(R.id.poi_detail);
        mPoiDetail.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
//				Intent intent = new Intent(PoiSearchActivity.this,
//						SearchDetailActivity.class);
//				intent.putExtra("poiitem", mPoi);
//				startActivity(intent);

            }
        });
        mPoiName = (TextView) findViewById(R.id.poi_name);
        mPoiAddress = (TextView) findViewById(R.id.poi_address);
        mListDataRv = (RecyclerView) findViewById(R.id.map_list);
        mListDataRv.setLayoutManager(new LinearLayoutManager(this));
        mGetUpLin = (LinearLayout) findViewById(R.id.lin_get_up);
        mNavBtn = (Button) findViewById(R.id.btn_way);

    }
    //-------- 定位 Start ------

    private void setUpMap() {
        if (mLocationClient == null) {
            mLocationClient = new AMapLocationClient(getApplicationContext());
            AMapLocationClientOption mLocationOption = new AMapLocationClientOption();
            //设置定位监听
            mLocationClient.setLocationListener(this);
            //设置为高精度定位模式
            mLocationOption.setOnceLocation(true);
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //设置定位参数
            mLocationClient.setLocationOption(mLocationOption);
            mLocationClient.startLocation();
        }
        // 自定义系统定位小蓝点
        MyLocationStyle myLocationStyle = new MyLocationStyle();
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory
                .fromResource(R.mipmap.point4));// 设置小蓝点的图标
        myLocationStyle.strokeColor(Color.BLACK);// 设置圆形的边框颜色
        myLocationStyle.radiusFillColor(Color.argb(100, 0, 0, 180));// 设置圆形的填充颜色
        myLocationStyle.strokeWidth(1.0f);// 设置圆形的边框粗细
        mAMap.setMyLocationStyle(myLocationStyle);
        mAMap.setLocationSource(this);// 设置定位监听
        mAMap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
        mAMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
    }
    /**
     * 开始进行poi搜索
     */
    /**
     * 开始进行poi搜索
     */
    protected void doSearchQuery() {
        if (!isSearch) {
            currentPage = 0;
            query = new PoiSearch.Query(keyWord, "", city);// 第一个参数表示搜索字符串，第二个参数表示poi搜索类型，第三个参数表示poi搜索区域（空字符串代表全国）
            query.setPageSize(20);// 设置每页最多返回多少条poiitem
            query.setPageNum(currentPage);// 设置查第一页

            if (lp != null) {
                poiSearch = new PoiSearch(this, query);
                poiSearch.setOnPoiSearchListener(this);
                poiSearch.setBound(new SearchBound(lp, 1000, true));//
                // 设置搜索区域为以lp点为圆心，其周围5000米范围
                poiSearch.searchPOIAsyn();// 异步搜索
            }
        } else {
            WaitingDialogControll.dismissWaitingDialog();
            mAMap.clear();

            mAMap.addMarker(new MarkerOptions()
                    .anchor(0.5f, 0.5f)
                    .icon(BitmapDescriptorFactory
                            .fromBitmap(BitmapFactory.decodeResource(
                                    getResources(), R.mipmap.near_position_sel)))
                    .position(new LatLng(searchData.getLat(), searchData.getLng())));
            mAMap.moveCamera(CameraUpdateFactory.zoomTo(13));
            mAMap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(searchData.getLat(), searchData.getLng())));
        }

    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onResume() {
        super.onResume();
        mapview.onResume();
        whetherToShowDetailInfo(false);
        mLocationClient.startLocation();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onPause() {
        super.onPause();
        mapview.onPause();
        if (mLocationClient != null) {
            mLocationClient.stopLocation();
        }

    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapview.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapview.onDestroy();
        if (mLocationClient != null) {
            mLocationClient.stopLocation();
        }

    }

    @Override
    public void onPoiItemSearched(PoiItem poiitem, int rcode) {

    }


    @Override
    public void onPoiSearched(PoiResult result, int rcode) {
        WaitingDialogControll.dismissWaitingDialog();
        if (rcode == AMapException.CODE_AMAP_SUCCESS) {
            if (result != null && result.getQuery() != null) {// 搜索poi的结果
                if (result.getQuery().equals(query)) {// 是否是同一条
                    poiResult = result;
                    poiItems = poiResult.getPois();// 取得第一页的poiitem数据，页数从数字0开始
                    setPoiResult();
                }
            } else {
            }
        } else {
        }
    }

    private void setPoiResult() {
        List<SuggestionCity> suggestionCities = poiResult
                .getSearchSuggestionCitys();// 当搜索不到poiitem数据时，会返回含有搜索关键字的城市信息
        if (poiItems != null && poiItems.size() > 0) {
            //清除POI信息显示
            whetherToShowDetailInfo(false);
            //并还原点击marker样式
            if (mlastMarker != null) {
                resetlastmarker();
            }
            //清理之前搜索结果的marker
            if (poiOverlay != null) {
                poiOverlay.removeFromMap();
            }
            mAMap.getMapScreenMarkers().clear();
            poiOverlay = new myPoiOverlay(mAMap, poiItems);
            poiOverlay.addToMap();
            poiOverlay.zoomToSpan();

//						mAMap.addMarker(new MarkerOptions()
//										.anchor(0.5f, 0.5f)
//										.icon(BitmapDescriptorFactory
//												.fromBitmap(BitmapFactory.decodeResource(
//														getResources(), R.mipmap.point4))));
//			mAMap.addMarker(new MarkerOptions()
//					.anchor(0.5f, 0.5f)
//					.icon(BitmapDescriptorFactory
//							.fromBitmap(BitmapFactory.decodeResource(
//									getResources(), R.mipmap.point4)))
//					.position(new LatLng(lp.getLatitude(), lp.getLongitude())));
            LocationListAdapter locationListAdapter = new LocationListAdapter(PoiAroundSearchActivity.this, poiItems);
            locationListAdapter.setOnItemClickListener(this);
            mListDataRv.setAdapter(locationListAdapter);
//						mAMap.addCircle(new CircleOptions()
//						.center(new LatLng(lp.getLatitude(),
//								lp.getLongitude())).radius(5000)
//						.strokeColor(Color.BLUE)
//						.fillColor(Color.argb(50, 1, 1, 1))
//						.strokeWidth(2));

        } else if (suggestionCities != null
                && suggestionCities.size() > 0) {
            showSuggestCity(suggestionCities);
        } else {
        }
    }

    PoiItem mCurrentPoi;

    @Override
    public boolean onMarkerClick(Marker marker) {
        if (!isSearch) {
            mListDataRv.setVisibility(View.GONE);
            mGetUpLin.setVisibility(View.VISIBLE);
            if (marker.getObject() != null) {
                whetherToShowDetailInfo(true);
                try {
                    mCurrentPoi = (PoiItem) marker.getObject();
                    if (mlastMarker == null) {
                        mlastMarker = marker;
                    } else {
                        // 将之前被点击的marker置为原来的状态
                        resetlastmarker();
                        mlastMarker = marker;
                    }
                    detailMarker = marker;
                    detailMarker.setIcon(BitmapDescriptorFactory
                            .fromBitmap(BitmapFactory.decodeResource(
                                    getResources(),
                                    R.mipmap.near_position_sel)));
                    setPoiItemDisplayContent(mCurrentPoi);
                } catch (Exception e) {
                    // TODO: handle exception
                }
            } else {
                whetherToShowDetailInfo(false);
                resetlastmarker();
            }
        }
        return true;
    }

    // 将之前被点击的marker置为原来的状态
    private void resetlastmarker() {
        int index = poiOverlay.getPoiIndex(mlastMarker);
        mlastMarker.setIcon(BitmapDescriptorFactory
                .fromBitmap(BitmapFactory.decodeResource(
                        getResources(),
                        markers)));
        mlastMarker = null;

    }


    private void setPoiItemDisplayContent(final PoiItem mCurrentPoi) {
        mPoiName.setText(mCurrentPoi.getTitle());
        mPoiAddress.setText(mCurrentPoi.getDistance() + "m " + mCurrentPoi.getSnippet());
    }

    @Override
    public View getInfoContents(Marker arg0) {
        return null;
    }

    @Override
    public View getInfoWindow(Marker arg0) {
        return null;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            default:
                break;
        }

    }

    private int markers = R.mipmap.near_position;

    private void whetherToShowDetailInfo(boolean isToShow) {
        if (!isSearch) {
            if (isToShow) {
                mPoiDetail.setVisibility(View.VISIBLE);

            } else {
                mPoiDetail.setVisibility(View.GONE);

            }
        } else {
            mPoiDetail.setVisibility(View.VISIBLE);
            mPoiName.setText(searchData.getTitle());
            mPoiAddress.setText(searchData.getDistance() + "m " + searchData.getSnip());
        }

    }

    @Override
    public void onMapClick(LatLng arg0) {
        if (!isSearch) {
            whetherToShowDetailInfo(false);
            if (mlastMarker != null) {
                resetlastmarker();
            }
        }

    }

    /**
     * poi没有搜索到数据，返回一些推荐城市的信息
     */
    private void showSuggestCity(List<SuggestionCity> cities) {
        String infomation = "推荐城市\n";
        for (int i = 0; i < cities.size(); i++) {
            infomation += "城市名称:" + cities.get(i).getCityName() + "城市区号:"
                    + cities.get(i).getCityCode() + "城市编码:"
                    + cities.get(i).getAdCode() + "\n";
        }

    }

    private class myPoiOverlay {
        private AMap mamap;
        private List<PoiItem> mPois;
        private ArrayList<Marker> mPoiMarks = new ArrayList<Marker>();

        public myPoiOverlay(AMap amap, List<PoiItem> pois) {
            mamap = amap;
            mPois = pois;
        }

        /**
         * 添加Marker到地图中。
         *
         * @since V2.1.0
         */
        public void addToMap() {
            for (int i = 0; i < mPois.size(); i++) {
                Marker marker = mamap.addMarker(getMarkerOptions(i));
                PoiItem item = mPois.get(i);
                marker.setObject(item);
                mPoiMarks.add(marker);
            }
        }

        /**
         * 去掉PoiOverlay上所有的Marker。
         *
         * @since V2.1.0
         */
        public void removeFromMap() {
            for (Marker mark : mPoiMarks) {
                mark.remove();

            }
        }

        /**
         * 移动镜头到当前的视角。
         *
         * @since V2.1.0
         */
        public void zoomToSpan() {
            mAMap.moveCamera(CameraUpdateFactory.zoomTo(15));
//            if (mPois != null && mPois.size() > 0) {
//                if (mamap == null)
//                    return;
//                LatLngBounds bounds = getLatLngBounds();
//                mamap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, 100));
//            }
        }

        private LatLngBounds getLatLngBounds() {
            LatLngBounds.Builder b = LatLngBounds.builder();
            for (int i = 0; i < mPois.size(); i++) {
                b.include(new LatLng(mPois.get(i).getLatLonPoint().getLatitude(),
                        mPois.get(i).getLatLonPoint().getLongitude()));
            }
            return b.build();
        }

        private MarkerOptions getMarkerOptions(int index) {
            return new MarkerOptions()
                    .position(
                            new LatLng(mPois.get(index).getLatLonPoint()
                                    .getLatitude(), mPois.get(index)
                                    .getLatLonPoint().getLongitude()))
                    .title(getTitle(index)).snippet(getSnippet(index))
                    .icon(getBitmapDescriptor(index));
        }

        protected String getTitle(int index) {
            return mPois.get(index).getTitle();
        }

        protected String getSnippet(int index) {
            return mPois.get(index).getSnippet();
        }

        /**
         * 从marker中得到poi在list的位置。
         *
         * @param marker 一个标记的对象。
         * @return 返回该marker对应的poi在list的位置。
         * @since V2.1.0
         */
        public int getPoiIndex(Marker marker) {
            for (int i = 0; i < mPoiMarks.size(); i++) {
                if (mPoiMarks.get(i).equals(marker)) {
                    return i;
                }
            }
            return -1;
        }

        /**
         * 返回第index的poi的信息。
         *
         * @param index 第几个poi。
         * @return poi的信息。poi对象详见搜索服务模块的基础核心包（com.amap.api.services.core）中的类 <strong><a href="../../../../../../Search/com/amap/api/services/core/PoiItem.html" title="com.amap.api.services.core中的类">PoiItem</a></strong>。
         * @since V2.1.0
         */
        public PoiItem getPoiItem(int index) {
            if (index < 0 || index >= mPois.size()) {
                return null;
            }
            return mPois.get(index);
        }

        protected BitmapDescriptor getBitmapDescriptor(int arg0) {
            BitmapDescriptor icon = BitmapDescriptorFactory.fromBitmap(
                    BitmapFactory.decodeResource(getResources(), markers));
            return icon;
        }


    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (mListener != null && aMapLocation != null) {
            if (aMapLocation.getErrorCode() == 0) {
                // 显示我的位置
                mListener.onLocationChanged(aMapLocation);
                //设置第一次焦点中心
                lp = new LatLonPoint(aMapLocation.getLatitude(), aMapLocation.getLongitude());
                city = aMapLocation.getCity();
                doSearchQuery();
            } else {
                String errText = "定位失败," + aMapLocation.getErrorCode() + ": " + aMapLocation.getErrorInfo();
                Log.e("AmapErr", errText);
            }
        }
    }

    @Override
    public void activate(OnLocationChangedListener listener) {
        mListener = listener;
        mLocationClient.startLocation();
    }

    @Override
    public void deactivate() {
        mListener = null;
        if (mLocationClient != null) {
            mLocationClient.stopLocation();
            mLocationClient.onDestroy();
        }
        mLocationClient = null;
    }

    @Override
    public void onItemClick(View view, int position) {
        //直接导航
        //步行模式 3
        //驾车模式 2
        int routeType = 2;// 标识为驾车模式
        Intent intent = new Intent(this, AccountStartNaviActivity.class);
        //终点
        intent.putExtra("getGdLat", String.valueOf(poiItems.get(position).getLatLonPoint().getLatitude()));
        intent.putExtra("getGdLng", String.valueOf(poiItems.get(position).getLatLonPoint().getLongitude()));
        //起点
        intent.putExtra("startGdLat", String.valueOf(lp.getLatitude()));
        intent.putExtra("startGdlng", String.valueOf(lp.getLongitude()));
        //驾车方式
        intent.putExtra("routeType", routeType);

        startActivity(intent);
    }

    @Override
    public void onItemLongClick(View view, int position) {

    }
}
